package com.sixth.service.impl;

import com.auth0.jwt.JWT;
import com.auth0.jwt.JWTVerifier;
import com.auth0.jwt.algorithms.Algorithm;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.sixth.dao.AclPermissionDao;
import com.sixth.dao.AclRoleDao;
import com.sixth.dao.AclUserDao;
import com.sixth.entity.*;
import com.sixth.dao.PermissionDao;
import com.sixth.service.PermissionService;
import com.sixth.until.CommonResult;
import com.sixth.until.OrderNoUtil;
import com.sixth.until.TableResult;
import com.sixth.until.WebUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.stereotype.Service;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.*;

/**
 * @program: self-tui-education
 * @description:
 * @author: 高振杨
 * @create: 2022-04-14 18:14
 **/
@Service
public class PermissionServiceImpl implements PermissionService {
    @Autowired
    private PermissionDao permissionDao;
    @Autowired
    private AclPermissionDao aclPermissionDao;
    @Autowired
    private AclUserDao aclUserDao;
    @Autowired
    private PasswordEncoder passwordEncoder;
    @Autowired
    private AclRoleDao roleDao;
    @Override
    public List<Permission> getPermissionByUserid(String userid) {
        //根据用户id查询权限
     List<Permission> permissions=permissionDao.selectByUserid(userid);
     return permissions;
    }

    //表示根据当前用户查询该用户具有的菜单
    @Override
    public CommonResult findMenuByUserid() {
        String token = WebUtil.getRequest().getHeader("token");

        //System.out.println(token);

        JWTVerifier build = JWT.require(Algorithm.HMAC256("gzy-lpp")).build();
        String userid = build.verify(token).getClaim("userid").asString();
        List<Permission> permissions = permissionDao.selectMenuByUserid(userid);
        //为菜单分层--父子关系
        List<Permission> first=new ArrayList<>();

        //找到一级菜单
        for (Permission f:permissions) {
            if(f.getPid().equals("1")){
                first.add(f);
            }
        }

        System.out.println(first);

        //方法的递归调用.
        for(Permission one:first){
            List<Permission> children = findChildren(permissions, one.getId());
            one.setChildren(children);
        }


        return new CommonResult(2000,"查询左侧菜单成功",first);
    }

    @Override
    public TableResult getUserByPage(Integer currentPage, Integer pageSize, UserVo user) {
        PageHelper.startPage(currentPage,pageSize);
        String startTime=null;
        String editTime=null;
        String username = user.getUsername();
        Date gmtCreate = user.getStartDate();
        Date gmtModified = user.getEndDate();

        if (gmtCreate!=null||gmtModified!=null){
            //System.out.println("进入if");

            SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd");
            try {
                String create = gmtCreate +"";
                String modified = gmtModified +"";

                System.out.println(username+"  modified:   "+modified+"  create:   "+create);

                Date format1 = new Date(create);
                Date format2 = new Date(modified);
                String start = format.format(format1);
                String edit = format.format(format2);
                startTime = format.parse(start).toLocaleString();
                editTime = format.parse(edit).toLocaleString();

//                System.out.println("输出name和时间");
//
//                System.out.println(username+"     "+startTime+"     "+editTime);

                List<AclUser> users= aclUserDao.getUserByPage(username,startTime,editTime);
                //System.out.println(users);
                PageInfo<AclUser> pageInfo = new PageInfo<>(users);
                return new TableResult(2000,"查询成功",pageInfo.getTotal(),pageInfo.getList());
            } catch (ParseException e) {
                e.printStackTrace();
            }
        }

       // System.out.println("准备进入aclUserDao");
        List<AclUser> users= aclUserDao.getUserByPage(username,startTime,editTime);
        //System.out.println(users);
        PageInfo<AclUser> pageInfo = new PageInfo<>(users);
        return new TableResult(2000,"查询成功",pageInfo.getTotal(),pageInfo.getList());
    }

    @Override
    public CommonResult updateUserByUser(AclUser user) {
        String username = user.getUsername();
        String nickName = user.getNickName();
        Date date = new Date();
        //String start = format.format(date);

        Date gmtModified = user.getGmtModified();
        gmtModified=date;
        String id = user.getId();
        int i =aclUserDao.updateUserByUser(username,nickName,id,gmtModified);
        if (i>0){
            return new CommonResult(2000,"编辑成功",null);
        }
        return new CommonResult(5000,"编辑失败",null);
    }

    @Override
    public CommonResult deleteUserById(String id) {

        //System.out.println(id+"+++++++++++++++++++++++++++++");
        int i=aclUserDao.deleteUserById(id);
        if (i>0){
            return new CommonResult(2000,"删除成功",null);
        }
        return new CommonResult(5000,"删除失败",null);
    }

    @Override
    public CommonResult updateUserStatusByid(String id, String deleted) {

       int i= aclUserDao.updateUserStatusByid(deleted,id);
        if (i>0){
            return new CommonResult(2000,"修改成功",null);
        }
        return new CommonResult(5000,"修改失败",null);
    }

    @Override
    public CommonResult addUserByUser(AclUser user) {
        String encode = passwordEncoder.encode("123456");
        user.setPassword(encode);

        int i=aclUserDao.selectcount();
        //String id = i + "";
        int id = i+1;
        user.setId(id+"");
        user.setSalt("aaaaaa");
        user.setIsDeleted(0);

        //SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd");
        Date date = new Date();
        //String start = format.format(date);

        user.setGmtCreate(date);
        user.setGmtModified(date);
        int j =aclUserDao.addUserByUser(user);

        if (j>0){
            return new CommonResult(2000,"添加成功",null);
        }
        return new CommonResult(5000,"添加失败",null);
    }

    @Override
    public TableResult findRoleByPage(Integer currentPage, Integer pageSize, AclRole role) {
        PageHelper.startPage(currentPage,pageSize);
        String roleName = role.getRoleName();
        Integer isDeleted = role.getIsDeleted();
        List<AclRole> roles=roleDao.findRoleByPage(roleName,isDeleted);
        //System.out.println(roles);
        PageInfo<AclRole> pageInfo = new PageInfo<>(roles);
        return new TableResult(2000,"查询成功",pageInfo.getTotal(),pageInfo.getList());
    }

    @Override
    public CommonResult updateRoleStatusByid(String id, String deleted) {
       int i= roleDao.updateRoleStatusByid(id,deleted);
        if (i>0){
            return new CommonResult(2000,"修改成功",null);
        }
        return new CommonResult(5000,"修改失败",null);
    }

    @Override
    public TableResult findAllpermissionByPage(Integer currentPage, Integer pageSize, AclPermission permission) {
        PageHelper.startPage(currentPage,pageSize);

        List<AclPermission> permissions = aclPermissionDao.findAll();

        System.out.println("permissions +++++++++++"+permissions);

        List<AclPermission> first=new ArrayList<>();
        String name = permission.getName();
        List<AclPermission> aclPermissions = aclPermissionDao.findAllpermissionByPage(name);

        if (name.equals("")) {
            //找到一级菜单
            for (AclPermission f:permissions) {
                if(f.getPid().equals("1")){
                    f.setTypeName("目录");
                    first.add(f);
                }
            }

            System.out.println("first+++++++++++++++++++++"+first);
            //方法的递归调用.
            for(AclPermission one:first){
                List<AclPermission> children = findChildrenByTypeName(permissions, one.getId());
                one.setChildren(children);
                for (AclPermission child : one.getChildren()) {
                    List<AclPermission> childrenByTypeName = findChildrenByTypeName(permissions, child.getId());
                    child.setChildren(childrenByTypeName);
                    //System.out.println("child+++++++++++++"+child);
                }
                //System.out.println("one++++++++++++"+one);
            }
        }else {
            //找到一级菜单
            for (AclPermission f:permissions) {
                if (f.getName().equals(name)) {
                    if (f.getPid().equals("1") && f.getType().equals(1)) {
                        f.setTypeName("目录");
                    }
                    if (f.getType().equals(1)) {
                        f.setTypeName("菜单");
                    }
                    if (f.getType().equals(2)) {
                        f.setTypeName("按钮");
                    }
                    first.add(f);
                }
            }

//            System.out.println("first+++++++++++++++++++++"+first);

            //方法的递归调用.
            for(AclPermission one:first){
                List<AclPermission> children = findChildrenByTypeName(permissions, one.getId());
                one.setChildren(children);
                for (AclPermission child : one.getChildren()) {
                    List<AclPermission> childrenByTypeName = findChildrenByTypeName(permissions, child.getId());
                    child.setChildren(childrenByTypeName);
                }
            }

        }
        PageInfo<AclPermission> pageInfo = new PageInfo<>(first);
        return new TableResult(2000,"查询成功",pageInfo.getTotal(),pageInfo.getList());
    }

    //查询对应菜单的子菜单和按钮 递归方法 一定要小心出现死循环
    public List<AclPermission> findChildrenByTypeName(List<AclPermission> list,String pid){
        List<AclPermission> children=new ArrayList<>();
        for(AclPermission permission:list){
            if(permission.getPid().equals(pid)){
                if (permission.getType().equals(1)) {
                    permission.setTypeName("菜单");
                }
                if (permission.getType().equals(2)){
                    permission.setTypeName("按钮");
                }
                children.add(permission);
            }
        }
        for(AclPermission c:children){
            List<AclPermission> children1 = findChildrenByTypeName(list, c.getId());
            c.setChildren(children1);
        }
        return children;
    }

    @Override
    public CommonResult permissioninsert(AclPermission permission) {

        int selectcount = aclPermissionDao.selectcount();
        int keyid = selectcount + 1;
        permission.setId(keyid+"");
        permission.setIsDeleted(0);
        Date date = new Date();
        permission.setGmtCreate(date);
        permission.setGmtModified(date);
        System.out.println(permission);
        int i = aclPermissionDao.insertSelective(permission);
        return new CommonResult(2000,"添加成功",null);
    }

    @Override
    public CommonResult deleteById(DeletePermission permission) {
        String[] permissionIds = permission.getPermissionIds();
        List<String> result = new ArrayList<>();
        HashSet<String> hashSet = new HashSet<String>();
        for (String ids :permissionIds) {
            result.add(ids);
        }
        hashSet.addAll(result);
        for (String id :hashSet) {
            aclPermissionDao.deleteByPrimaryKey(id);
        }
        return new CommonResult(2000,"删除成功",null);

    }

    @Override
    public CommonResult findPermissionByRoleId(String roleId) {
        Map<String,Object> map=new LinkedHashMap<>();
        List<AclPermission> permissions=aclPermissionDao.findAll();
        List<AclPermission> first = new ArrayList<>();

        //找到一级菜单
        for (AclPermission aclpermission:permissions) {
            if (aclpermission.getPid().equals("1")){
                first.add(aclpermission);
            }
        }
        //方法的递归调用.
        for(AclPermission one:first){
            List<AclPermission> children = findroleChildren(permissions, one.getId());
            one.setChildren(children);
        }
        List<String> strings = aclPermissionDao.selectFindAllByRoleId(roleId);
        map.put("allPermissions",first);
        map.put("checkItems",strings);
        return new CommonResult(2000,"查询成功",map);
    }

    @Override
    public CommonResult confirmFenPermission(PermissionVo permissionVo) {

        String roleId = permissionVo.getRoleId();
        aclPermissionDao.deleteByRoleid(roleId);
        String[] permissionIds = permissionVo.getPermissionIds();
        for (String permissionId: permissionIds) {
            Date date = new Date();
            String id = OrderNoUtil.getOrderNo();
            int row=aclPermissionDao.insertRolePermission(id,roleId,permissionId,date);
        }
        return new CommonResult(2000,"分配成功",null);
    }

    @Override
    public CommonResult update(AclPermission permission) {
        int i = aclPermissionDao.updateByPrimaryKeySelective(permission);
        if (i>0){
            return new CommonResult(2000,"修改成功",null);
        }
        return new CommonResult(5000,"修改失败",null);
    }

    //查询对应菜单的子菜单 递归方法 一定要小心出现死循环
    public List<AclPermission> findroleChildren(List<AclPermission> list,String pid){
        List<AclPermission> children=new ArrayList<>();
        for(AclPermission permission:list){
            if(permission.getPid().equals(pid)){
                children.add(permission);
            }
        }

        for(AclPermission c:children){
            List<AclPermission> children1 = findroleChildren(list, c.getId());
            c.setChildren(children1);
        }
        return children;
    }

    //查询对应菜单的子菜单 递归方法 一定要小心出现死循环
    public List<Permission> findChildren(List<Permission> list,String pid){
        List<Permission> children=new ArrayList<>();
        for(Permission permission:list){
            if(permission.getPid().equals(pid)){
                children.add(permission);
            }
        }

        for(Permission c:children){
            List<Permission> children1 = findChildren(list, c.getId());
            c.setChildren(children1);
        }
        return children;
    }
}
